package com.weishi.project.training.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.weishi.common.enums.TrainingProgramEnum;
import com.weishi.common.utils.DateUtils;
import com.weishi.common.utils.StringUtils;
import com.weishi.common.utils.poi.ExcelUtil;
import com.weishi.framework.aspectj.lang.annotation.Log;
import com.weishi.framework.aspectj.lang.enums.BusinessType;
import com.weishi.framework.web.controller.BaseController;
import com.weishi.framework.web.domain.AjaxResult;
import com.weishi.framework.web.page.TableDataInfo;
import com.weishi.project.api.controller.selection.WeekPlanMethod;
import com.weishi.project.api.vo.appvo.SubsectionDTO;
import com.weishi.project.mcs8.Mcs8Cilent;
import com.weishi.project.training.domain.*;
import com.weishi.project.training.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * 训练小组航道Controller
 */
@Api(value = "训练小组航道", description = "训练小组航道")
@RestController
@CrossOrigin("*")//解决移动端跨域
@RequestMapping("/trainingGroupChannel/trainingGroupChannel")
public class TrainingGroupChannelController extends BaseController {

    @Autowired
    private ITrainingGroupChannelService trainingGroupChannelService;

    /**
     * 运动员 接口
     */
    @Autowired
    private ISportsmanService sportsmanService;

    /**
     * 运动员成绩 接口
     */
    @Autowired
    private ITrainingAchievementService trainingAchievementService;

    /**
     * 分段成绩 接口
     */
    @Autowired
    private IDynamometerSubsectionService dynamometerSubsectionService;

    /**
     * 训练课 接口
     */
    @Autowired
    private ITrainingDayService trainingDayService;

    /**
     * 训练组 接口
     */
    @Autowired
    private ITrainingGroupService trainingGroupService;

    /**
     * 赛后数据表接口
     */
    @Autowired
    private IRaceDataService raceDataService;

    /**
     * 水上分段 接口
     */
    @Autowired
    private IHeartRateCountService heartRateCountService;

    /**
     * 测功仪成绩排名 接口
     */
    @Autowired
    private IDynamometerRankingService dynamometerRankingService;

    @Autowired
    private IHeartRateRecordService heartRateRecordService;

    /**
     * 测功仪历史数据，接口
     */
    @Autowired
    private IDynamometerService dynamometerService;


    /**
     * 根据艇只查询水上成绩
     */
    @PreAuthorize("@ss.hasPermi('trainingGroupChannel:trainingGroupChannel:list')")
    @GetMapping("/list")
    public TableDataInfo list(TrainingGroupChannel trainingGroupChannel) {
        if (trainingGroupChannel.getRowingKilometersTwo() == null) {
            trainingGroupChannel.setRowingKilometers(0);
        } else {
            trainingGroupChannel.setRowingKilometers(trainingGroupChannel.getRowingKilometersTwo());
        }
        if ("".equals(trainingGroupChannel.getBoatType())) {
            trainingGroupChannel.setBoatType(null);
        }

        startPage();
        List<TrainingGroupChannel> list = trainingGroupChannelService.selectTrainingGroupChannelList(trainingGroupChannel);

        List<DynamometerSubsection> dynamometerSubsectionList = dynamometerSubsectionService
                .list(Wrappers.<DynamometerSubsection>lambdaQuery()
                        .eq(DynamometerSubsection::getGroupId, trainingGroupChannel.getGroupId()));

        // 判断
        if (list.size() > 0) {
            List<TrainingAchievement> achievements = trainingAchievementService
                    .list(Wrappers.<TrainingAchievement>lambdaQuery()
                            .eq(TrainingAchievement::getGroupId, trainingGroupChannel.getGroupId()));
            Map<Integer, List<TrainingAchievement>> map = new HashMap<>();
            for (TrainingAchievement achievement : achievements) {
                List<TrainingAchievement> temp = map.get(achievement.getChannelId());
                if (temp == null) {
                    temp = new ArrayList<>();
                    map.put(achievement.getChannelId(), temp);
                }
                temp.add(achievement);
            }
            list.forEach(p -> {
                // 陆上成绩
                if (p.getFirstLevel().equals("land_specific_training_dynamometer")) {
                    // 设置存储运动员 id 的容器
                    List<TrainingAchievement> trainingAchievementList = map.get(p.getId());
                    if (trainingAchievementList != null) {
                        // 设置存储运动员 名称 的容器
                        Integer sportsmanId = 0;
                        List<String> sportsmanName = new ArrayList<>();
                        for (TrainingAchievement achievement : trainingAchievementList) {
                            sportsmanId = achievement.getSportsmanId();
                            sportsmanName.add(sportsmanService.qrySportsmanNameById(sportsmanId,true).getName() + " ");
                            try {
                                p.setAverageHeartRate(achievement.getHeartRate()!=null?Integer.parseInt(achievement.getHeartRate()) : 0);
                            } catch (NumberFormatException e) {
                                p.setAverageHeartRate(0);
                            }
                        }

                        // 存入 运动员名称
                        p.setSportsmanName(sportsmanName);
                        p.setSportsmanId(sportsmanId);

                        // 查询分段成绩

                        // 平均桨频
                        Integer averagePropellerFrequency = 0;
                        int size = 0;
                        // 分段成绩 集合数量
                        int dynamometerSubsectionListSize = dynamometerSubsectionList.size();
                        for (int g = 0; g < dynamometerSubsectionListSize; g++) {
                            if (StringUtils.isNotNull(dynamometerSubsectionList.get(g).getPropellerFrequency()) && !"".equals(dynamometerSubsectionList.get(g).getPropellerFrequency())) {
                                if (dynamometerSubsectionList.get(g).getSportsmanId().equals(sportsmanId)) {
                                    averagePropellerFrequency += Integer.parseInt(dynamometerSubsectionList.get(g).getPropellerFrequency());
                                    size++;
                                }
                            }
                        }
                        // 存储平均桨频
                        if (averagePropellerFrequency > 0 && size > 0) {
                            p.setAveragePropellerFrequency(averagePropellerFrequency / size);
                        }

                        // 设置平均瓦特
                        Integer averageWatt = 0;
                        int size2 = 0;
                        for (int g = 0; g < dynamometerSubsectionListSize; g++) {
                            if (StringUtils.isNotNull(dynamometerSubsectionList.get(g).getWatt()) && !"".equals(dynamometerSubsectionList.get(g).getWatt())) {
                                if (dynamometerSubsectionList.get(g).getSportsmanId().equals(sportsmanId)) {
                                    averageWatt += Integer.parseInt(dynamometerSubsectionList.get(g).getWatt());
                                    size2++;
                                }
                            }
                        }
                        // 存储平均瓦特
                        if (averageWatt > 0 && size2 > 0) {
                            Integer averageWatts = averageWatt / size2;
                            p.setAverageWatt(averageWatts.toString());
                        }

                        // 设置平均功率
                        Integer averagePower = 0;
                        int size3 = 0;
                        for (int g = 0; g < dynamometerSubsectionListSize; g++) {
                            if (StringUtils.isNotNull(dynamometerSubsectionList.get(g).getPower()) && !"".equals(dynamometerSubsectionList.get(g).getPower())) {
                                if (dynamometerSubsectionList.get(g).getSportsmanId().equals(sportsmanId)) {
                                    averagePower += (int) StringUtils.turnSecond(dynamometerSubsectionList.get(g).getPower());
                                    size3++;
                                }
                            }
                        }
                        // 存储平均功率
                        if (averagePower > 0 && size3 > 0) {
                            Integer averagePowers = averagePower / size3;
                            p.setPower(StringUtils.millisecondRotationTime(averagePowers));
                        }

                        // 平均心率
                        Integer averageHeartRate = 0;
                        int size4 = 0;
                        for (int g = 0; g < dynamometerSubsectionListSize; g++) {
                            if (StringUtils.isNotNull(dynamometerSubsectionList.get(g).getHeartRate())) {
                                if (dynamometerSubsectionList.get(g).getSportsmanId().equals(sportsmanId)) {
                                    averageHeartRate += dynamometerSubsectionList.get(g).getHeartRate();
                                }
                            }
                        }
                        // 存储平均心率
                        if (averageHeartRate > 0 && size4 > 0) {
                            Integer averageHeartRates = averageHeartRate / size4;
                            p.setAverageHeartRate(averageHeartRates);
                        }
                    }
                    // 水上成绩
                } else if (p.getFirstLevel().equals("special_training_water")) {
                    // 设置存储运动员 id 的容器
                    List<TrainingAchievement> trainingAchievementList = map.get(p.getId());
                    if (trainingAchievementList != null) {
                        // 设置存储运动员 名称 的容器
                        List<String> sportsmanName = new ArrayList<>();
                        for (TrainingAchievement achievement : trainingAchievementList) {
                            sportsmanName.add(sportsmanService.qrySportsmanNameById(achievement.getSportsmanId(),true).getName() + " ");
                        }

                        // 存入 运动员名称
                        p.setSportsmanName(sportsmanName);

                        // 计算平均桨频
                        if (!"".equals(p.getSegmentPropellerFrequency()) && StringUtils.isNotNull(p.getSegmentPropellerFrequency())) {
                            Double averageFrequency = 0.0;
                            List<String> averageFrequencyList = StringUtils.splitsSpace(p.getSegmentPropellerFrequency());
                            for (int a = 0; a < averageFrequencyList.size(); a++) {
                                averageFrequency += Double.parseDouble(averageFrequencyList.get(a));
                            }
                            p.setAveragePropellerFrequency(averageFrequency.intValue() / averageFrequencyList.size());
                        }

                        // 设置桨频
                        p.setPropellerFrequency(p.getSegmentPropellerFrequency());


                        /**
                         * 查询水上分段速度
                         */
                        List<HeartRateCount> heartRateCountList = heartRateCountService
                                .list(Wrappers.<HeartRateCount>lambdaQuery()
                                        .eq(HeartRateCount::getGroupId, p.getGroupId())
                                        .eq(HeartRateCount::getChannelId, p.getChannelId())
                                        .eq(HeartRateCount::getTrainingDayId, p.getTrainingDayId()));
                        // 设置分段速度
                        String sectionalSpeed = "";
                        for (int s = 0; s < heartRateCountList.size(); s++) {
                            if (StringUtils.isNotNull(heartRateCountList.get(s).getShipSpeed()) && heartRateCountList.get(s).getShipSpeed() > 0.0) {
                                sectionalSpeed += heartRateCountList.get(s).getShipSpeed() + " ";
                            }
                        }
                        // 存储分段速度
                        if (!"".equals(sectionalSpeed)) {
                            p.setSectionalSpeed(sectionalSpeed.substring(0, sectionalSpeed.length() - 1));
                        }

                        // 设置平均船速
                        Double sectionalSpeeds = 0.0;
                        for (int s = 0; s < heartRateCountList.size(); s++) {
                            if (StringUtils.isNotNull(heartRateCountList.get(s).getShipSpeed()) && heartRateCountList.get(s).getShipSpeed() > 0.0) {
                                sectionalSpeeds += heartRateCountList.get(s).getShipSpeed();
                            }
                        }
                        if (StringUtils.isNotNull(sectionalSpeeds) && sectionalSpeeds > 0.0) {
                            Double sectionalSpeeds2 = sectionalSpeeds / heartRateCountList.size();
                            // 平均船速
                            p.setAverageSpeed(String.format("%.2f", sectionalSpeeds2));
                        }

                        // 设置分段桨频
                        String segmentPropellerFrequency = "";
                        for (int s = 0; s < heartRateCountList.size(); s++) {
                            if (StringUtils.isNotNull(heartRateCountList.get(s).getPropellerFrequency()) && !"".equals(heartRateCountList.get(s).getPropellerFrequency())) {
                                segmentPropellerFrequency += heartRateCountList.get(s).getPropellerFrequency() + " ";
                            }
                        }
                        if (!"".equals(segmentPropellerFrequency)) {
                            p.setSegmentPropellerFrequency(segmentPropellerFrequency.substring(0, segmentPropellerFrequency.length() - 1));
                        }

                        // 设置平均桨频
                        Double averageFrequency = 0.0;
                        for (int s = 0; s < heartRateCountList.size(); s++) {
                            if (StringUtils.isNotNull(heartRateCountList.get(s).getPropellerFrequency()) && !"".equals(heartRateCountList.get(s).getPropellerFrequency())) {
                                averageFrequency += Double.parseDouble(heartRateCountList.get(s).getPropellerFrequency());
                            }
                        }
                        // 存储 平均桨频
                        if (StringUtils.isNotNull(averageFrequency) && averageFrequency > 0.0) {
                            Integer averagePropellerFrequency = averageFrequency.intValue() / heartRateCountList.size();
                            p.setAveragePropellerFrequency(averagePropellerFrequency);
                        }


                        if (p.getTrainingMode() == 1) {
                            // 重新赋值总成绩
                            // 计算总成绩
                            Double totalDistance = 0.0;
                            for (int s = 0; s < heartRateCountList.size(); s++) {
                                if (StringUtils.isNotNull(heartRateCountList.get(s).getTotalDistance()) && heartRateCountList.get(s).getTotalDistance() > 0.0) {
                                    totalDistance += heartRateCountList.get(s).getTotalDistance();
                                }
                            }
                            if (totalDistance > 0.0) {
                                p.setAchievement(totalDistance.toString());
                            }

                            // 重新赋值分段成绩
                            String segmentedTiming = "";
                            for (int s = 0; s < heartRateCountList.size(); s++) {
                                if (StringUtils.isNotNull(heartRateCountList.get(s).getTotalDistance()) && heartRateCountList.get(s).getTotalDistance() > 0.0) {
                                    segmentedTiming += heartRateCountList.get(s).getTotalDistance() + " ";
                                }
                            }
                            if (!"".equals(segmentedTiming)) {
                                p.setSegmentedTiming(segmentedTiming.substring(0, segmentedTiming.length() - 1));
                            }
                        }
                    }
                }
            });

            if(list.get(0).getFirstLevel().equals("land_specific_training_dynamometer")){
                //按固定人排序
                Collections.sort(list, new Comparator<TrainingGroupChannel>() {
                    @Override
                    public int compare(TrainingGroupChannel o1, TrainingGroupChannel o2) {
                        //降序排序
                        int s1 = o1.getSportsmanId()==null ? 1000 : o1.getSportsmanId();
                        int s2 = o2.getSportsmanId()==null ? 1000 : o2.getSportsmanId();
                        return s1 - s2;
                    }
                });
            }
        }
        return getDataTable(list);
    }

    /**
     * 导出训练小组航道列表
     */
    @PreAuthorize("@ss.hasPermi('trainingGroupChannel:trainingGroupChannel:export')")
    @Log(title = "训练小组航道", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(TrainingGroupChannel trainingGroupChannel) {

        List<TrainingGroupChannel> list = trainingGroupChannelService.selectTrainingGroupChannelList(trainingGroupChannel);

        // 查询所有运动员
        List<Sportsman> sportsmanList = sportsmanService.list();

        // 判断
        if (list.size() > 0) {
            list.forEach(p -> {
                // 陆上成绩
                if (p.getFirstLevel().equals("land_specific_training_dynamometer")) {
                    // 水上成绩
                } else if (p.getFirstLevel().equals("special_training_water")) {

                    List<TrainingAchievement> trainingAchievementList = trainingAchievementService
                            .list(Wrappers.<TrainingAchievement>lambdaQuery()
                                    .eq(TrainingAchievement::getChannelId, p.getId()));

                    // 设置存储运动员 名称 的容器
                    List<String> sportsmanName = new ArrayList<>();
                    for (int j = 0; j < trainingAchievementList.size(); j++) {
                        for (int g = 0; g < sportsmanList.size(); g++) {
                            if (trainingAchievementList.get(j).getSportsmanId().equals(sportsmanList.get(g).getId())) {
                                sportsmanName.add(sportsmanList.get(g).getName() + " ");
                            }
                        }
                    }

                    // 根据 运动员的 id 查询运动员的名称 并且放到返回值中
                    // 存入 运动员名称
                    String sportsmanNames = "";
                    if (sportsmanName.size() > 0) {
                        for (int s = 0; s < sportsmanName.size(); s++) {
                            sportsmanNames += sportsmanName.get(s) + " ";
                        }
                    }
                    p.setSportsmanNames(sportsmanNames);

                    // 计算平均桨频
                    if (!"".equals(p.getSegmentPropellerFrequency()) && StringUtils.isNotNull(p.getSegmentPropellerFrequency())) {
                        Double averageFrequency = 0.0;
                        System.out.println();
                        List<String> averageFrequencyList = StringUtils.splitsSpace(p.getSegmentPropellerFrequency());
                        for (int a = 0; a < averageFrequencyList.size(); a++) {
                            averageFrequency += Double.parseDouble(averageFrequencyList.get(a));
                        }
                        p.setAveragePropellerFrequency(averageFrequency.intValue() / averageFrequencyList.size());
                    }

                    // 设置桨频
                    p.setPropellerFrequency(p.getSegmentPropellerFrequency());

                    // 设置小组名称
                    if (StringUtils.isNotNull(p.getBatch())) {
                        Integer batch = p.getBatch() + 1;
                        p.setBatchName("小组" + batch);
                    }

                    // 设置航道名称
                    if (!"".equals(p.getChannelName()) && StringUtils.isNotNull(p.getChannelName())) {
                        Integer channelName = Integer.parseInt(p.getChannelName()) + 1;
                        p.setChannelName("第" + channelName + "航道");
                    }


                    // 设置分段成绩
                    if (!"".equals(p.getSegmentedTiming()) && StringUtils.isNotNull(p.getSegmentedTiming())) {
                        String segmentedTiming = "";
                        Integer segmentedTimingIndex = 0;  // 分段成绩下标
                        List<String> segmentedTimingList = StringUtils.splitsSpace(p.getSegmentedTiming());
                        for (int s = 0; s < segmentedTimingList.size(); s++) {
                            segmentedTimingIndex++;
                            segmentedTiming += "分段成绩" + segmentedTimingIndex + ": " + segmentedTimingList.get(s) + String.valueOf((char) 10);
                        }
                        p.setSegmentedTiming(segmentedTiming);
                    }


                    /**
                     * 查询水上分段数据
                     */
                    List<HeartRateCount> heartRateCountList = heartRateCountService
                            .list(Wrappers.<HeartRateCount>lambdaQuery()
                                    .eq(HeartRateCount::getGroupId, p.getGroupId())
                                    .eq(HeartRateCount::getChannelId, p.getChannelId())
                                    .eq(HeartRateCount::getTrainingDayId, p.getTrainingDayId()));
                    // 设置分段速度
                    String sectionalSpeed = "";
                    // 分段船速下标
                    int indexSpeed = 1;
                    for (int s = 0; s < heartRateCountList.size(); s++) {
                        if (StringUtils.isNotNull(heartRateCountList.get(s).getShipSpeed()) && heartRateCountList.get(s).getShipSpeed() > 0.0) {
                            sectionalSpeed += "分段船速" + indexSpeed + "：" + heartRateCountList.get(s).getShipSpeed() + " " + String.valueOf((char) 10);
                            indexSpeed++;
                        }
                    }
                    // 存储分段速度
                    if (StringUtils.isNotNull(sectionalSpeed) && !"".equals(sectionalSpeed)) {
                        p.setSectionalSpeed(sectionalSpeed.substring(0, sectionalSpeed.length() - 1));
                    }

                    // 设置平均船速
                    Double sectionalSpeeds = 0.0;
                    for (int s = 0; s < heartRateCountList.size(); s++) {
                        if (StringUtils.isNotNull(heartRateCountList.get(s).getShipSpeed()) && heartRateCountList.get(s).getShipSpeed() > 0.0) {
                            sectionalSpeeds += heartRateCountList.get(s).getShipSpeed();
                        }
                    }

                    if (sectionalSpeeds > 0.0) {
                        Double sectionalSpeeds2 = sectionalSpeeds / heartRateCountList.size();
                        // 平均船速
                        p.setAverageSpeed(String.format("%.2f", sectionalSpeeds2));
                    }

                    // 设置分段桨频
                    String segmentPropellerFrequency = "";
                    // 分段桨频下标
                    int indexFrequency = 1;
                    for (int s = 0; s < heartRateCountList.size(); s++) {
                        if (StringUtils.isNotNull(heartRateCountList.get(s).getPropellerFrequency()) && !"".equals(heartRateCountList.get(s).getPropellerFrequency())) {
                            segmentPropellerFrequency += "分段桨频" + indexFrequency + "：" + heartRateCountList.get(s).getPropellerFrequency() + " " + String.valueOf((char) 10);
                            indexFrequency++;
                        }
                    }
                    if (!"".equals(segmentPropellerFrequency)) {
                        p.setSegmentPropellerFrequency(segmentPropellerFrequency.substring(0, segmentPropellerFrequency.length() - 1));
                    }

                    // 设置平均桨频
                    Double averageFrequency = 0.0;
                    for (int s = 0; s < heartRateCountList.size(); s++) {
                        if (StringUtils.isNotNull(heartRateCountList.get(s).getPropellerFrequency()) && !"".equals(heartRateCountList.get(s).getPropellerFrequency())) {
                            averageFrequency += Double.parseDouble(heartRateCountList.get(s).getPropellerFrequency());
                        }
                    }
                    // 存储 平均桨频
                    if (StringUtils.isNotNull(averageFrequency) && averageFrequency > 0.0) {
                        Integer averagePropellerFrequencys = averageFrequency.intValue() / heartRateCountList.size();
                        p.setAveragePropellerFrequency(averagePropellerFrequencys);
                    }


                    for (int m = 0; m < heartRateCountList.size(); m++) {
                        // 分段心率
                        String segmentHeartRate = "";
                        // 分段心率下标
                        int indexHeartRate = 1;
                        // 平均心率
                        Integer averageHeartRate = 0;
                        List<HeartRateRecord> heartRateRecordList = heartRateRecordService
                                .list(Wrappers.<HeartRateRecord>lambdaQuery()
                                        .eq(HeartRateRecord::getHeartRateCountId, heartRateCountList.get(m).getId()));
                        for (int k = 0; k < heartRateRecordList.size(); k++) {
                            if (StringUtils.isNotNull(heartRateRecordList.get(k).getHeartRateAvg())) {
                                segmentHeartRate += "分段心率" + indexHeartRate + "：" + heartRateRecordList.get(k).getHeartRateAvg() + " " + String.valueOf((char) 10);
                                indexHeartRate++;
                                averageHeartRate += heartRateRecordList.get(k).getHeartRateAvg();
                            }
                        }
                        // 设置分段心率
                        if (!"".equals(segmentHeartRate)) {
                            p.setSegmentHeartRate(segmentHeartRate.substring(0, segmentHeartRate.length() - 1));
                        }
                        if (averageHeartRate > 0) {
                            p.setAverageHeartRate(averageHeartRate / heartRateRecordList.size());
                        }
                    }


                }
            });
        }

        ExcelUtil<TrainingGroupChannel> util = new ExcelUtil<>(TrainingGroupChannel.class);
        return util.exportExcel(list, "训练成绩");
    }

    /**
     * 获取训练小组航道基本信息
     */
    @PreAuthorize("@ss.hasPermi('trainingGroupChannel:trainingGroupChannel:query')")
    @GetMapping("/{id}")
    public AjaxResult getBaseInfo(@PathVariable("id") Integer id) {
        return AjaxResult.success(trainingGroupChannelService.getTrainingGroupChannelDetails(id));
    }

    /**
     * 获取训练小组航道+运动员成绩详细信息
     */
    @GetMapping("/getInfo/{id}")
    public AjaxResult getInfo(@PathVariable("id") Integer id) {
        return AjaxResult.success(trainingGroupChannelService.getTrainingGroupChannelAndAchievement(id));
    }

    /**
     * 新增训练小组航道
     */
    @Transactional
    @PreAuthorize("@ss.hasPermi('trainingGroupChannel:trainingGroupChannel:add')")
    @Log(title = "训练小组航道", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TrainingGroupChannel trainingGroupChannel) {
        // 更新课程 实际划船距离
        TrainingDay trainingMode = trainingDayService.getById(trainingGroupChannel.getTrainingDayId());
        TrainingDay trainingDay = new TrainingDay();
        trainingDay.setKilometers(trainingGroupChannel.getRowingKilometers());
        trainingDay.setTrainingMode(trainingMode.getTrainingMode());
        trainingDay.setClassHour(trainingMode.getClassHour());
        trainingDay.setCompletion(trainingMode.getCompletion());
        trainingDay.setRealClassHour(trainingMode.getRealClassHour());
        trainingDay.setId(trainingGroupChannel.getTrainingDayId());
        trainingDayService.updateById(trainingDay);

        trainingGroupChannel.setCtime(new Date());
        String userName = "";
        List<TrainingAchievement> userNameList = trainingGroupChannel.getPerson();
        for (int j = 0; j < userNameList.size(); j++) {
            userName += sportsmanService.getById(userNameList.get(j).getSportsmanId()).getName() + ",";
        }

        trainingGroupChannel.setChannelInfoStr(trainingGroupChannel.getBoatType() + ":" + userName);
        trainingGroupChannel.setPropellerFrequency(trainingGroupChannel.getSegmentPropellerFrequency());
        trainingGroupChannel.setTrainingMode(trainingMode.getTrainingMode());
        trainingGroupChannelService.add(trainingGroupChannel);

        // 更新小组里面的距离
        TrainingGroup trainingGroup = new TrainingGroup();
        trainingGroup.setKilometer(trainingGroupChannel.getRowingKilometers());
        trainingGroup.setId(trainingGroupChannel.getGroupId());
        trainingGroupService.updateById(trainingGroup);

        //异步汇总训练项目数据
        trainingDayService.aggregateData(trainingGroupChannel.getTrainingDayId());
        return AjaxResult.success();
    }

    /**
     * 修改训练小组航道
     */
    @Transactional
    @PreAuthorize("@ss.hasPermi('trainingGroupChannel:trainingGroupChannel:edit')")
    @Log(title = "训练小组航道", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TrainingGroupChannel trainingGroupChannel) {
        // 更新课程 实际划船距离
        TrainingDay trainingMode = trainingDayService.getById(trainingGroupChannel.getTrainingDayId());
        TrainingDay trainingDay = new TrainingDay();
        trainingDay.setKilometers(trainingGroupChannel.getRowingKilometers());
        trainingDay.setTrainingMode(trainingMode.getTrainingMode());
        trainingDay.setClassHour(trainingMode.getClassHour());
        trainingDay.setCompletion(trainingMode.getCompletion());
        trainingDay.setId(trainingGroupChannel.getTrainingDayId());
        trainingDayService.updateById(trainingDay);

        trainingGroupChannel.setCtime(new Date());
        String userName = "";
        Integer sportsmanId = 0;
        List<TrainingAchievement> achievements = trainingGroupChannel.getPerson();
        for (TrainingAchievement achievement : achievements) {
            sportsmanId = achievement.getSportsmanId();
            Sportsman sportsman = sportsmanService.getById(achievement.getSportsmanId());
            userName += sportsman.getName() + ",";
            achievement.setSportsmanName(sportsman.getName());
            trainingAchievementService.updateById(achievement);
        }
        trainingGroupChannel.setChannelInfoStr(trainingGroupChannel.getBoatType() + ":" + userName);
        trainingGroupChannel.setPropellerFrequency(trainingGroupChannel.getSegmentPropellerFrequency());
        trainingGroupChannelService.saveOrUpdate(trainingGroupChannel);

        // 更新小组里面的距离
        TrainingGroup trainingGroup = new TrainingGroup();
        trainingGroup.setKilometer(trainingGroupChannel.getRowingKilometers());
        trainingGroup.setId(trainingGroupChannel.getGroupId());
        trainingGroupService.updateById(trainingGroup);

        //异步汇总训练项目数据
        trainingDayService.aggregateData(trainingGroupChannel.getTrainingDayId());

        if (trainingMode.getFirstLevel().equals(TrainingProgramEnum.LANDSPECIFICTRAININGDYNAMOMETER.getKey())) {
            // 更新 tbl_dynamometer_ranking 表数据
            DynamometerRanking dynamometerRanking = dynamometerRankingService
                    .getOne(Wrappers.<DynamometerRanking>lambdaQuery()
                            .eq(DynamometerRanking::getChannelId, trainingGroupChannel.getId()));
            dynamometerRanking.setMileage(trainingGroupChannel.getRowingKilometers());
            dynamometerRanking.setSportsmanId(sportsmanId.longValue());
            dynamometerRankingService.updateById(dynamometerRanking);
        }
        return AjaxResult.success();
    }

    /**
     * 删除训练小组航道
     */
    @PreAuthorize("@ss.hasPermi('trainingGroupChannel:trainingGroupChannel:remove')")
    @Log(title = "训练小组航道", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Integer[] ids) {
        trainingGroupChannelService.removeByIds(Arrays.asList(ids));
        return AjaxResult.success();
    }

    @PreAuthorize("@ss.hasPermi('trainingGroupChannel:trainingGroupChannel:list')")
    @GetMapping("/getChannelNameList")
    public TableDataInfo getChannelNameList(TrainingGroupChannel trainingGroupChannel) {
        startPage();
        List<TrainingGroupChannel> list = trainingGroupChannelService.getChannelNameList();
        return getDataTable(list);
    }


    @ApiOperation("PC 端 -- 新增赛后数据")
    @RequestMapping(value = "/addRaceData", method = RequestMethod.POST)
    public AjaxResult addRaceData(@RequestBody JSONObject jsonObject) {
        // 查询运动员详情
        Sportsman sportsman = sportsmanService.getById(Integer.parseInt(jsonObject.get("sportsmanId").toString()));

        // 查询前端发送的 list 数据
        com.alibaba.fastjson.JSONArray jsonArray = jsonObject.getJSONArray("list");
        List<RaceData> raceDataList = JSON.parseArray(jsonArray.toString(), RaceData.class);
        if (raceDataList.size() > 0) {
            raceDataList.forEach(p -> {
                RaceData raceData = new RaceData();
                System.out.println();
                StringUtils.copyProperties(p, raceData);
                raceData.setSportsmanId(sportsman.getId());
                raceData.setSportsmanName(sportsman.getName());
                raceData.setSportsmanSex(sportsman.getSex());
                System.out.println();
                raceData.setCtime(new Date());
                raceData.setTrainingDayId(Integer.parseInt(jsonObject.get("trainingDayId").toString()));
                raceData.setGroupId(Integer.parseInt(jsonObject.get("groupId").toString()));
                raceDataService.save(raceData);
            });
        }
        return AjaxResult.success();
    }


    @ApiOperation("PC 端 -- 查询赛后数据")
    @RequestMapping(value = "/getRaceDataList", method = RequestMethod.GET)
    public AjaxResult getRaceDataList(HttpServletRequest request) {
        String sportsmanId = request.getParameter("sportsmanId");
        String trainingDayId = request.getParameter("trainingDayId");
        String groupId = request.getParameter("groupId");
        return AjaxResult.success(Optional.ofNullable(raceDataService
                .list(Wrappers.<RaceData>lambdaQuery()
                        .eq(RaceData::getSportsmanId, Integer.parseInt(sportsmanId))
                        .eq(RaceData::getTrainingDayId, Integer.parseInt(trainingDayId))
                        .eq(RaceData::getGroupId, Integer.parseInt(groupId)))));
    }


    @ApiOperation("PC 端 -- 修改赛后数据")
    @RequestMapping(value = "/updateRaceData", method = RequestMethod.POST)
    public AjaxResult updateRaceData(@RequestBody JSONObject jsonObject) {

        /**
         * 修改就是将之前的数据删掉，然后重新新增
         */
        List<RaceData> raceDataList2 = raceDataService
                .list(Wrappers.<RaceData>lambdaQuery()
                        .eq(RaceData::getSportsmanId, Integer.parseInt(jsonObject.get("sportsmanId").toString()))
                        .eq(RaceData::getTrainingDayId, Integer.parseInt(jsonObject.get("trainingDayId").toString()))
                        .eq(RaceData::getGroupId, Integer.parseInt(jsonObject.get("groupId").toString())));

        // 删除数据
        if (raceDataList2.size() > 0) {
            raceDataList2.forEach(p -> {
                raceDataService.removeById(p.getId());
            });
        }

        // 查询运动员详情
        Sportsman sportsman = sportsmanService.getById(Integer.parseInt(jsonObject.get("sportsmanId").toString()));

        // 查询前端发送的 list 数据
        com.alibaba.fastjson.JSONArray jsonArray = jsonObject.getJSONArray("list");
        List<RaceData> raceDataList = JSON.parseArray(jsonArray.toString(), RaceData.class);
        if (raceDataList.size() > 0) {
            System.out.println();
            raceDataList.forEach(p -> {
                System.out.println();
                RaceData raceData = new RaceData();
                System.out.println();
                StringUtils.copyProperties(p, raceData);
                raceData.setSportsmanId(sportsman.getId());
                raceData.setSportsmanName(sportsman.getName());
                raceData.setSportsmanSex(sportsman.getSex());
                raceData.setCtime(new Date());
                raceData.setTrainingDayId(Integer.parseInt(jsonObject.get("trainingDayId").toString()));
                raceData.setGroupId(Integer.parseInt(jsonObject.get("groupId").toString()));
                raceDataService.save(raceData);
            });
        }
        return AjaxResult.success();
    }


    @ApiOperation("PC 端 -- 查询航道视频历史数据")
    @RequestMapping(value = "/getRaceDataList", method = RequestMethod.POST)
    public AjaxResult getRaceDataList(@RequestBody JSONObject jsonObject) {
        if (StringUtils.isNull(jsonObject.get("deviceId"))
                || StringUtils.isNull(jsonObject.get("stime"))
                || StringUtils.isNull(jsonObject.get("etime"))) {

            return AjaxResult.success();
        } else {
            Mcs8Cilent mcs8Cilent = Mcs8Cilent.getInstant();
            List<String> list = mcs8Cilent.getHistoryFileList(jsonObject.get("deviceId").toString(), DateUtils.lastOrAfterHour(jsonObject.get("stime").toString(), -5), DateUtils.lastOrAfterHour(jsonObject.get("etime").toString(), 5), 0, 10);
            if (list != null && list.size() > 0) {
                return AjaxResult.success("请求成功！", list);
            } else {
                return AjaxResult.success();
            }
        }
    }


    @Transactional
    @ApiOperation("PC 端 -- 修改航道水上陆上分段数据")
    @RequestMapping(value = "/updateSubsection", method = RequestMethod.POST)
    public AjaxResult updateSubsection(@RequestBody JSONObject jsonObject) {
        TrainingDay trainingDay = trainingDayService.getById(Integer.parseInt(jsonObject.get("trainingDayId").toString()));
        int trainingMode = trainingDay.getTrainingMode();


        // 接收前端发送的 list 陆上数据
        JSONArray jsonArray = jsonObject.getJSONArray("list");
        List<SubsectionDTO> subsectionList = JSON.parseArray(jsonArray.toString(), SubsectionDTO.class);

        //使用Collections集合工具类进行排序
        Collections.sort(subsectionList, new Comparator<SubsectionDTO>() {
            @Override
            public int compare(SubsectionDTO o1, SubsectionDTO o2) {
                //升序排序，降序反写
                return o1.getStage() - o2.getStage();
            }
        });

        TrainingGroupChannel trainingGroupChannel = trainingGroupChannelService.getById(Integer.parseInt(jsonObject.get("channelId").toString()));

        int size = 0;
        // 判断水上
        if (jsonObject.get("firstLevel").equals(TrainingProgramEnum.WATERPROJECT.getKey())) {
            /**
             * 更新航道信息
             */
            // 分段成绩
            String segmentedTimings = "";
            // 最大船速
            double maxSpeed = 0.0;
            double avgSpeed = 0.0;
            double speedTotal = 0.0;

            for (SubsectionDTO dto : subsectionList) {
                //PC 端新增分段成绩和心率
                dto.setChannelId(trainingGroupChannel.getId());
                dto.setGroupId(trainingGroupChannel.getGroupId());
                dto.setTrainingDayId(Integer.parseInt(jsonObject.get("trainingDayId").toString()));
                heartRateCountService.addOrSaveHeartRateCount(WeekPlanMethod.addOrSaveHeartRateCount(dto));

                segmentedTimings += dto.getLengthTime() + " ";
                if (dto.getSpeed() != null && dto.getSpeed() > maxSpeed) {
                    maxSpeed = dto.getSpeed();
                    speedTotal += dto.getSpeed().doubleValue();
                }
            }
            // 更新分段成绩
            trainingGroupChannel.setSegmentedTiming(segmentedTimings.substring(0, segmentedTimings.length() - 1));
            // 更新总成绩
            if (trainingMode == 0) {
                if (subsectionList.size() > 0) {
                    trainingGroupChannel.setAchievement(subsectionList.get(subsectionList.size() - 1).getLengthTime());
                }
            } else {
                if (subsectionList.size() > 0) {
                    trainingGroupChannel.setAchievement(subsectionList.get(subsectionList.size() - 1).getMileage().toString());
                }
            }

            // 更新水上成绩毫秒值
            trainingGroupChannel.setAchievementMs(new Long(StringUtils.turnSecond(subsectionList.get(subsectionList.size() - 1).getLengthTime())).intValue());

            // 最大船速
            trainingGroupChannel.setMaxSpeed(String.valueOf(maxSpeed));
            trainingGroupChannel.setSpeed(avgSpeed);
            trainingGroupChannel.setAverageSpeed(subsectionList.size() > 0 ? String.valueOf(speedTotal / subsectionList.size()) : "0");
            // 循环出多个人
            if (subsectionList.size() > 0) {
                subsectionList.forEach(p -> {
                    if (p.getPerson().size() > 0) p.getPerson().forEach(n -> {
                        TrainingAchievement trainingAchievement = new TrainingAchievement();

                        List<Integer> countList = new ArrayList<>();
                        // 查询水上分段最大心率
                        List<HeartRateCount> heartRateCountList = heartRateCountService
                                .list(Wrappers.<HeartRateCount>lambdaQuery()
                                        .eq(HeartRateCount::getChannelId, trainingGroupChannel.getId()));
                        if (heartRateCountList.size() > 0) heartRateCountList.forEach(h -> {
                            countList.add(h.getId());
                        });
                        List<HeartRateRecord> heartRateRecordList = heartRateRecordService
                                .list(Wrappers.<HeartRateRecord>lambdaQuery()
                                        .in(HeartRateRecord::getHeartRateCountId, countList)
                                        .eq(HeartRateRecord::getSportsmanId, n.getSportsmanId())
                                        .orderByDesc(HeartRateRecord::getHeartRateAvg));
                        // 存储最大心率
                        if (heartRateRecordList.size() > 0) {
                            trainingAchievement.setMaxHeartRate(heartRateRecordList.get(0).getHeartRateAvg());
                        }
                        trainingAchievement.setId(trainingAchievementService
                                .getOne(Wrappers.<TrainingAchievement>lambdaQuery()
                                        .eq(TrainingAchievement::getChannelId, trainingGroupChannel.getId())
                                        .eq(TrainingAchievement::getSportsmanId, n.getSportsmanId())).getId());
                        trainingAchievementService.saveOrUpdate(trainingAchievement);
                    });
                });
            }

        } else {
            // 陆上数据
            // 分段成绩
            List<String> segmentedTiming = new ArrayList<>();
            // 分段功率
            Integer averagePower = 0;
            List<String> segmentPower = new ArrayList<>();

            // 接收 分段瓦特
            Integer averageWatt = 0;
            List<String> segmentWatt = new ArrayList<>();

            Integer averagePropellerFrequency = 0;
            List<String> segmentPropellerFrequency = new ArrayList<>();
            //接收 分段桨频
            String propellerFrequency = "";
            double propellerFrequencyTotal = 0;
            // 更新分段成绩
            String segmentedTimings = "";
            // 设置总成绩
            Long lengthTime3 = 0L;

            // 接收 分段心率
            int averageHeartRateTotal = 0;
            int maxHeartRate = 0;

            // 总距离
            double mileage = 0.0;
            for (SubsectionDTO dto : subsectionList) {
                mileage += dto.getMileage();

                segmentedTiming.add(dto.getLengthTime());
                segmentedTimings += dto.getLengthTime() + " ";
                lengthTime3 += StringUtils.turnSecond(dto.getLengthTime());

                segmentPower.add(dto.getPower());
                averagePower += (int) StringUtils.turnSecond(dto.getPower());
                averageWatt += Integer.parseInt(dto.getWatt());
                segmentWatt.add(dto.getWatt());

                segmentPropellerFrequency.add(dto.getPropellerFrequency());
                averagePropellerFrequency += Integer.parseInt(dto.getPropellerFrequency());
                propellerFrequency += dto.getPropellerFrequency() + " ";
                propellerFrequencyTotal += StringUtils.isNotEmpty(dto.getPropellerFrequency()) ? Double.parseDouble(dto.getPropellerFrequency()) : 0.0;
                int hr = StringUtils.isNotEmpty(dto.getPerson()) ? dto.getPerson().get(0).getHeartRate() : 0;
                averageHeartRateTotal += hr;
                if (hr > maxHeartRate) {
                    maxHeartRate = hr;
                }
            }

            // 更新总成绩
            if (lengthTime3 > 0L) {
                if (trainingMode == 0) {
                    trainingGroupChannel.setAchievement(StringUtils.millisecondRotationTime(lengthTime3));
                } else {
                    trainingGroupChannel.setAchievement(String.valueOf(mileage));
                    trainingGroupChannel.setRowingKilometers((int) mileage);
                }
            }
            //跟新航道相关数据
            trainingGroupChannel.setSegmentedTiming(segmentedTimings.substring(0, segmentedTimings.length() - 1));
            trainingGroupChannel.setPower(StringUtils.millisecondRotationTime(averagePower / subsectionList.size()));
            Integer watts = averageWatt / subsectionList.size();
            trainingGroupChannel.setWatt(watts.toString());
            trainingGroupChannel.setAverageFrequency(propellerFrequencyTotal / subsectionList.size());
            trainingGroupChannel.setPropellerFrequency(propellerFrequency);

            int length = subsectionList.size();

            List<Map<String, Object>> jsondate = new ArrayList<>();
            Dynamometer dynamometer = new Dynamometer();
            // 分段距离相加距离
            double mileages = 0.0;
            Integer sportsmanId = 0;
            for (int i = 0; i < length; i++) {
                mileages += subsectionList.get(i).getMileage();
                DynamometerSubsection dynamometerSubsection = new DynamometerSubsection();
                StringUtils.copyProperties(subsectionList.get(i), dynamometerSubsection);
                dynamometerSubsection.setCtime(new Date());
                if (trainingMode == 0) {
                    dynamometerSubsection.setMileage(subsectionList.get(i).getMileage());
                    dynamometerSubsection.setLengthTime(WeekPlanMethod.timeAdd(segmentedTiming, size, i, trainingMode));
                    size++;
                } else {
                    dynamometerSubsection.setMileage(mileages);
                    dynamometerSubsection.setLengthTime(subsectionList.get(i).getLengthTime());
                    size++;
                }
                dynamometerSubsection.setSegmentNumber(size); // 分段数
                // 查询运动员信息
                Sportsman sportsman = sportsmanService.getById(subsectionList.get(i).getPerson().get(0).getSportsmanId());
                sportsmanId = sportsman.getId();
                if (StringUtils.isNotNull(sportsman)) dynamometerSubsection.setSportsmanName(sportsman.getName());
                dynamometerSubsection.setSex(sportsman.getSex());
                dynamometerSubsection.setTrainingMode(trainingMode);
                dynamometerSubsection.setSegmentNumber(subsectionList.get(i).getStage());
                dynamometerSubsection.setSportsmanId(sportsman.getId());
                dynamometerSubsection.setTrainingDayId(Integer.parseInt(jsonObject.get("trainingDayId").toString()));
                dynamometerSubsection.setChannelId(Integer.parseInt(jsonObject.get("channelId").toString()));
                dynamometerSubsection.setGroupId(trainingGroupChannel.getGroupId());
                dynamometerSubsection.setHeartRate(subsectionList.get(i).getPerson().get(0).getHeartRate());
                DynamometerSubsection dynamometerSubsection1 = dynamometerSubsectionService.getById(subsectionList.get(i).getId());
                if (StringUtils.isNotNull(dynamometerSubsection1) && dynamometerSubsection1.getPeakForce() > 0.0) {
                    dynamometerSubsection.setPeakForce(dynamometerSubsection1.getPeakForce());
                }
                if (StringUtils.isNotNull(dynamometerSubsection1)) {
                    dynamometerSubsection.setAverageForce(dynamometerSubsection1.getAverageForce());
                }

                // 更新测功仪历史数据
                StringUtils.copyProperties(dynamometerSubsection, dynamometer);
                Map<String, Object> temp = new HashMap<>();
                temp.put("mileage", dynamometer.getMileage());
                temp.put("propellerFrequency", dynamometer.getPropellerFrequency());
                temp.put("heartRate", dynamometer.getHeartRate() == null ? 0 : dynamometer.getHeartRate());
                temp.put("lengthTime", dynamometer.getLengthTime());
                temp.put("speed", dynamometer.getSpeed() == null ? 0.0 : dynamometer.getSpeed());
                temp.put("power", dynamometer.getPower());
                temp.put("watt", dynamometer.getWatt());
                temp.put("peakForce", dynamometer.getPeakForce() == null ? 0.0 : dynamometer.getPeakForce());
                temp.put("averageForce", dynamometer.getAverageForce() == null ? 0.0 : dynamometer.getAverageForce());
                temp.put("pulpNumber", dynamometer.getPulpNumber() == null ? 0 : dynamometer.getPulpNumber());
                temp.put("trainingMode", dynamometer.getTrainingMode() == null ? 0.0 : dynamometer.getTrainingMode());
                temp.put("segmentNumber", dynamometer.getSegmentNumber() == null ? 0.0 : dynamometer.getSegmentNumber());
                jsondate.add(temp);

                // 更新分段历史数据
                dynamometerSubsectionService.saveOrUpdate(dynamometerSubsection);
            }

            List<DynamometerSubsection> dynamometerSubsectionsLimit1 = dynamometerSubsectionService
                    .list(Wrappers.<DynamometerSubsection>lambdaQuery()
                            .eq(DynamometerSubsection::getSportsmanId, sportsmanId)
                            .eq(DynamometerSubsection::getGroupId, trainingGroupChannel.getGroupId())
                            .orderByAsc(DynamometerSubsection::getId));
            if (dynamometerSubsectionsLimit1.size() > 0) {
                dynamometerSubsectionsLimit1.get(0).setJsonData(JSONArray.toJSONString(jsondate));
                dynamometerSubsectionService.updateById(dynamometerSubsectionsLimit1.get(0));
            }

            // 查询运动员信息
            Sportsman sportsman = sportsmanService.getById(subsectionList.get(0).getPerson().get(0).getSportsmanId());
            DynamometerRanking dynamometerRankingGetOne = dynamometerRankingService
                    .getOne(Wrappers.<DynamometerRanking>lambdaQuery()
                            .eq(DynamometerRanking::getGroupId, trainingGroupChannel.getGroupId())
                            .eq(DynamometerRanking::getSportsmanId, sportsman.getId()));

            // 添加分段成绩只加一条数据
            DynamometerRanking dynamometerRanking = new DynamometerRanking();
            if (StringUtils.isNotNull(dynamometerRankingGetOne)) {
                dynamometerRanking.setId(dynamometerRankingGetOne.getId());
            }
            // 设置总成绩
            Long lengthTime4 = 0L;
            for (int i = 0; i < segmentedTiming.size(); i++) {
                lengthTime4 += DateUtils.getLongTime(segmentedTiming.get(i));
            }
            dynamometerRanking.setChannelId(trainingGroupChannel.getId().longValue());
            dynamometerRanking.setSportsmanId(Long.parseLong(subsectionList.get(0).getPerson().get(0).getSportsmanId().toString()));
            // 更新总成绩
            if (trainingMode == 0) {
                dynamometerRanking.setMileage(trainingGroupChannel.getRowingKilometers()); // 总里程
                if (lengthTime4 > 0L) {
                    dynamometerRanking.setLengthTime(DateUtils.getStringTime_HHmmss_SS(lengthTime4));
                }
            } else {
                dynamometerRanking.setMileage(mileage); // 总里程
                dynamometerRanking.setLengthTime(subsectionList.get(subsectionList.size() - 1).getLengthTime());
            }

            Integer averagePowers = averagePower / segmentPower.size();
            dynamometerRanking.setPower(StringUtils.millisecondRotationTime(averagePowers)); // 分段功率
            Integer averageWatts = averageWatt / segmentWatt.size();
            dynamometerRanking.setWatt(averageWatts.toString()); // 分段瓦特
            Long l = (long) size;
            dynamometerRanking.setSegmentNumber(l); // 分段总数
            Long ls = (long) trainingMode;
            dynamometerRanking.setTrainingMode(ls);
            if (StringUtils.isNotNull(sportsman)) dynamometerRanking.setSportsmanName(sportsman.getName());
            dynamometerRanking.setSex(Long.parseLong(sportsman.getSex().toString()));
            Integer averagePropellerFrequencys = averagePropellerFrequency / segmentPropellerFrequency.size();
            dynamometerRanking.setPropellerFrequency(averagePropellerFrequencys.toString());
            dynamometerRanking.setTrainingDayId(Long.parseLong(jsonObject.get("trainingDayId").toString()));
            dynamometerRanking.setCtime(new Date());
            dynamometerRanking.setGroupId(trainingGroupChannel.getGroupId().longValue());
            Integer hertRate = averageHeartRateTotal / length;
            Long hertRateLong = (long) hertRate;
            dynamometerRanking.setHeartRate(hertRateLong);
            dynamometerRanking.setSegmentNumber((long) length);
            dynamometerRanking.setTimeMillisecond(StringUtils.turnSecond(subsectionList.get(subsectionList.size() - 1).getLengthTime()));
            dynamometerRankingService.saveOrUpdate(dynamometerRanking);


            /**
             * 更新航道信息
             */

            // 根据航道 id 更新最大心率
            TrainingAchievement trainingAchievement = new TrainingAchievement();
            trainingAchievement.setMaxHeartRate(maxHeartRate);
            trainingAchievement.setHeartRate(String.valueOf(averageHeartRateTotal / length));
            trainingAchievement.setId(trainingAchievementService
                    .getOne(Wrappers.<TrainingAchievement>lambdaQuery()
                            .eq(TrainingAchievement::getChannelId, trainingGroupChannel.getId())
                            .eq(TrainingAchievement::getTrainingDayId, Integer.parseInt(jsonObject.get("trainingDayId").toString()))).getId());
            trainingAchievementService.saveOrUpdate(trainingAchievement);

        }

        //同步跟新航道信息
        trainingGroupChannelService.updateById(trainingGroupChannel);

        return AjaxResult.success();
    }


    @ApiOperation("PC 端 -- 查询航道水上陆上分段数据")
    @RequestMapping(value = "/getSubsection", method = RequestMethod.POST)
    public AjaxResult getSubsection(@RequestBody JSONObject jsonObject) {
        return trainingGroupChannelService.getSubsection(jsonObject);
    }


    @ApiOperation("PC 端 -- 删除水上或者陆上分段数据")
    @RequestMapping(value = "/deleteSubsection", method = RequestMethod.POST)
    public AjaxResult deleteSubsection(@RequestBody JSONObject jsonObject) {
        trainingGroupChannelService.deleteSubsection(jsonObject);
        return AjaxResult.success();
    }


    @ApiOperation("PC 端 -- 清空航道下关联的数据，以及航道数据")
    @RequestMapping(value = "/emptyChannel", method = RequestMethod.POST)
    public AjaxResult emptyChannel(@RequestBody JSONObject jsonObject) {
        trainingGroupChannelService.emptyChannel(jsonObject);
        return AjaxResult.success();
    }

}